#include <iostream>
#include "XThreadPool.h"
#include "XFtpServerCMD.h"
#include <event2/event.h>
#include <event2/listener.h>
#include <event2/bufferevent.h>
using namespace std;

void 
listen_cb(evconnlistener* listen, 
		  evutil_socket_t sock, 
		  struct sockaddr* client_addr, 
		  int cli_len, void* arg)
{
	cout << "listen_cb" << endl;
	XTask *task = new XFtpServerCMD();
	task->sock_ = sock;
	XThreadPool::Get()->Dispatch(task);
}

int main()
{
#ifdef _WIN32
	WSADATA wsa;
	WSAStartup(MAKEWORD(2, 2), &wsa);
#else
	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
	{
		return 1;
	}
#endif
	
	XThreadPool::Get()->Init(10);

	cout << "test thread pool\n";

	event_base* base = event_base_new();
	if (base)
	{
		cout << "event_base_new success!\n";
	}

	struct sockaddr_in serv;
	serv.sin_family = AF_INET;
	serv.sin_port = htons(8000);
	serv.sin_addr.s_addr = htonl(INADDR_ANY);
	evconnlistener* listen = evconnlistener_new_bind(base,
		listen_cb, base,
		LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE,
		10, (struct sockaddr*)&serv, sizeof(serv));

	if (base)
	{
		event_base_dispatch(base);
	}
	if (listen)
	{
		evconnlistener_free(listen);
	}
	if (base)
	{
		event_base_free(base);
	}

#ifdef _WIN32
	WSACleanup();
#endif
	return 0;
}